package ansible

import (
	"bytes"
	"fmt"
	"github.com/golang/glog"
	v3 "github.com/kylelemons/go-gypsy/yaml"
	v2 "gopkg.in/yaml.v2"
	"io"
	"strings"
	"unicode"
)

type Task interface{}

type Command struct {
	Name    string
	Command string
}

type PlayBook struct {
	Hosts string
	Tasks []Task
}

type Handler struct {
	Name string
}

type Reader interface {
	Read() ([]byte, error)
}

type YAMLToJSONDecoder struct {
	reader Reader
}

func GeneratePlayBook(hosts string, cmd string) []byte {
	task := Command{
		Name:    "start kubelet",
		Command: cmd,
	}

	playBook := PlayBook{
		Hosts: hosts,
		Tasks: []Task{task},
	}
	out, err := v2.Marshal([]PlayBook{playBook})
	if err != nil {
		glog.Error(err)
	}
	return out
}

func YamlToJson(path string) {
	yamlReader := ""
	objs := yamlReader.Read()
	config, err := v3.ReadFile(path)
	if err != nil {
		fmt.Println("err:", err)
	}
	fmt.Println(config)
}

var separator = "---"

type YAMLReader struct {
	reader Reader
}

// Read returns a full YAML document.
func (r *YAMLReader) Read() ([]byte, error) {
	var buffer bytes.Buffer
	for {
		line, err := r.reader.Read()
		if err != nil && err != io.EOF {
			return nil, err
		}

		sep := len([]byte(separator))
		if i := bytes.Index(line, []byte(separator)); i == 0 {
			// We have a potential document terminator
			i += sep
			after := line[i:]
			if len(strings.TrimRightFunc(string(after), unicode.IsSpace)) == 0 {
				if buffer.Len() != 0 {
					return buffer.Bytes(), nil
				}
				if err == io.EOF {
					return nil, err
				}
			}
		}
		if err == io.EOF {
			if buffer.Len() != 0 {
				// If we're at EOF, we have a final, non-terminated line. Return it.
				return buffer.Bytes(), nil
			}
			return nil, err
		}
		buffer.Write(line)
	}
}
